package org.finesys.common.core.provider;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.finesys.common.constants.ServerConstants;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.RestTemplateUtil;
import org.finesys.common.excel.enums.DictEnum;
import org.finesys.common.excel.handler.DictDataProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@RequiredArgsConstructor
@Slf4j
public class RemoteDictDataProvider implements DictDataProvider {

    private final LoadBalancerClient loadBalancerClient;
    private final RestTemplateUtil restTemplateUtil;

    @Override
    public DictEnum[] getDict(String type) {

        ServiceInstance serviceInstance = loadBalancerClient.choose(ServerConstants.SYSTEM_SERVER);
        String uri = "/dict/findType";
        String url = restTemplateUtil.buildUrl(serviceInstance.getScheme(), serviceInstance.getHost(),
                serviceInstance.getPort(), uri);
        Map<String, Object> uriVariable = new HashMap<>();
        uriVariable.put("type", type);
        R<List<Map<String, Object>>> result = restTemplateUtil.get(url, uriVariable, R.class).getBody();
        if (result == null) {
            String message = String.format("获取字典%s失败", type);
            if (log.isWarnEnabled()) {
                log.warn(message);
            }
            throw new RuntimeException(message);
        }
        List<Map<String, Object>> dictDataList = result.getData();
        if (CollUtil.isEmpty(dictDataList)) {
            return new DictEnum[0];
        }

        // 构建 DictEnum 数组
        DictEnum.Builder dictEnumBuilder = DictEnum.builder();
        for (Map<String, Object> dictData : dictDataList) {
            String value = MapUtil.getStr(dictData, "value");
            String label = MapUtil.getStr(dictData, "label");
            dictEnumBuilder.add(value, label);
        }

        return dictEnumBuilder.build();
    }
}
